package com.mzx.javase.thread.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 类描述：线程池，Executors类的使用
 *
 * @ClassName ThreadPoolDemo
 * @Description TODO
 * @Author 马子鑫
 * @Date 2022/8/7 14:53
 * @Version 1.0
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        //创建一个固定长度的线程池，当达到线程最大数量时，线程池规模将不再变化
//        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //创建一个可缓冲的线程池，如果当前线程池的规模超出了处理需求，将回收空的线程；当需求增加时，会增加线程数量；线程池规模无限制。
//        ExecutorService executorService = Executors.newCachedThreadPool();

        //创建一个单线程的Executor，确保任务对了，串行执行
//        ExecutorService executorService = Executors.newSingleThreadExecutor();
//        executorService.submit(myRunnable);
//        executorService.submit(myRunnable);
//        executorService.submit(myRunnable);
//        executorService.submit(myRunnable);
//        executorService.submit(myRunnable);

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        scheduledExecutorService.schedule(myRunnable, 3, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(myRunnable, 1, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(myRunnable, 2, TimeUnit.SECONDS);

        //关闭线程池
        scheduledExecutorService.shutdown();
        //isTerminated当调用shutdown()方法后，并且所有提交的任务完成后返回为true;
        while (!scheduledExecutorService.isTerminated()){

        }
        System.out.println("线程池关闭");



    }
}

/**
 * 定义一个线程类，实现runnable接口
 */
class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("我需要一个教练");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("教练来了：" +Thread.currentThread().getName());
        System.out.println("教练游回了游泳池");
    }
}
